using System;
using System.Diagnostics.Contracts;
using System.Runtime.Caching;

namespace OpenWaves.Caching
{
    public class MemoryCacheWrapper<T> : ICache<T> where T : class
    {
        private readonly string keyPrefix;
        private readonly MemoryCache innerCache;
        private readonly string regionName;

        public MemoryCacheWrapper(MemoryCache innerCache, string keyPrefix = null, string regionName = null)
        {
            Contract.Requires<ArgumentNullException>(innerCache != null);

            this.innerCache = innerCache;
            this.regionName = regionName;
            this.keyPrefix = keyPrefix;
        }

        public void InsertValue(string key, T value, DateTime absoluteExpiration)
        {
            if (this.keyPrefix != null)
                key = this.keyPrefix + "." + key;

            this.innerCache.Set(key, value, absoluteExpiration, this.regionName);
        }

        public void EvictValue(string key)
        {
            if (this.keyPrefix != null)
                key = this.keyPrefix + "." + key;

            this.innerCache.Remove(key, this.regionName);
        }

        public T GetValue(string key)
        {
            if (this.keyPrefix != null)
                key = this.keyPrefix + "." + key;

            return (T) this.innerCache.Get(key, this.regionName);
        }
    }
}